package org.example.multiThreading.Lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReentrantReadWriteLock {

    public static void main(String[] args) {

        //创建线程池
        ExecutorService service = Executors.newFixedThreadPool(5);
        //创建TestReadWriteLock
        TestReadWriteLock t = new TestReadWriteLock();
        //写两次
        for (int i = 0; i < 2; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    t.xie();
                }
            };
            service.execute(runnable);
        }
        //读18次
        for (int i = 0; i < 18; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    t.du();
                }
            };
            service.execute(runnable);
        }

        //关闭线程池
        service.shutdown();

    }

}

class TestReadWriteLock {
    //获取读写锁
    ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
    ReentrantReadWriteLock.ReadLock readLock=lock.readLock();//获得读锁
    ReentrantReadWriteLock.WriteLock writeLock=lock.writeLock();//获得写锁
    //值
    Integer values = 1000;

    public void xie(){
        //开启写锁
        writeLock.lock();
        try {
            Thread.sleep(4000);
            values-=1;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放写锁
            writeLock.unlock();
        }
    }

    public void du(){
        //开启读锁
        readLock.lock();
        try {
            System.out.println("当前vlues值"+values);
        } finally {
            //释放读锁
            readLock.unlock();
        }
    }

}
